package com.weibo.controller;

import com.weibo.entity.Blog;
import com.weibo.entity.BlogImg;
import com.weibo.entity.Comment;
import com.weibo.entity.User;
import com.weibo.resp.BlogDetailAndCommentsResp;
import com.weibo.resp.BlogListItemResp;
import com.weibo.service.BlogService;
import com.weibo.utils.ResponseResult;
import com.weibo.utils.enums.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    BlogService blogService;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    public ResponseResult getList(){
        HashMap<String,Object> param = new HashMap<>();
        List<BlogListItemResp> blogListItemResps = blogService.getList(param);
        return new ResponseResult(blogListItemResps);
    }

    @GetMapping("/one/{blogId}")
    public ResponseResult getOne(@PathVariable("blogId") int blogId){
        BlogDetailAndCommentsResp resp = blogService.getOne(blogId);
        return new ResponseResult(resp);
    }

    @PostMapping("/save")
    public ResponseResult save(MultipartHttpServletRequest request,String token){
        if(token == null || token.equals("") || token.equals("null")){
            return new ResponseResult(ResultCodeEnum.PREMISSION_ERROR);
        }
        if(!redisTemplate.hasKey(token)){
            return new ResponseResult(ResultCodeEnum.PREMISSION_ERROR);
        }
        User user = (User) redisTemplate.opsForValue().get(token);

        String content = request.getParameter("content");
        Blog blog = new Blog();
        blog.setContent(content);
        //TODO 用户id固定
        blog.setUserId(user.getUserId());
        blogService.add(blog);

        // 创建文件夹
        File uploadDir = new File(this.uploadDir);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            MultipartFile file = request.getFile(fileNames.next());

            if (file != null) {
                // 保存文件到指定路径
                String filePath = this.uploadDir + "/" + file.getOriginalFilename();
                File dest = new File(filePath);
                try {
                    file.transferTo(dest);
                    // 将文件路径添加到博客的文件列表中
                    BlogImg blogImg = new BlogImg();
                    blogImg.setBlogId(blog.getBlogId());
                    blogImg.setUrl(file.getOriginalFilename());
                    blogService.addImg(blogImg);
                } catch (IOException e) {
                    e.printStackTrace();
                    return new ResponseResult(ResultCodeEnum.SERVER_ERROR);
                }
            }
        }
        return new ResponseResult();
    }

    @PostMapping("/addcomment")
    public ResponseResult addComment(Comment comment,String token){
        if(token == null || token.equals("") || token.equals("null")){
            return new ResponseResult(ResultCodeEnum.PREMISSION_ERROR);
        }
        if(!redisTemplate.hasKey(token)){
            return new ResponseResult(ResultCodeEnum.PREMISSION_ERROR);
        }
        User user = (User) redisTemplate.opsForValue().get(token);
        // 用户编号从redis获取
        comment.setUserId(user.getUserId());
        blogService.addComment(comment);
        return new ResponseResult();
    }
}
